#include "votesys.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<time.h>

#define LOGFILE "vote.log"
countList list;
bool_t isVoteOpen = TRUE;

void vlog_result()
{
  FILE *f;
  time_t timer;
  u_long i;
  timer = time(NULL);
  f = fopen(LOGFILE, "a");
  
  fprintf(f, "election terminating at %s",
           asctime( localtime(&timer)) );
  for(i=0; i<list.num; i++)
  {
    fprintf(f, " %d vote(s) %s\n", list.array[i].count, list.array[i].name); 
  }
  fclose(f);
}


bool_t
closevote_1_svc(void *x, void *y, struct svc_req *rqstp)
{
   isVoteOpen = FALSE; 
   vlog_result();
   return TRUE; 
}


void wlog(char *name)
{
   FILE *f;       
   time_t timer;
   f = fopen(LOGFILE, "a");
   timer = time(NULL);
   fprintf(f, "vote for %s at %s", 
           name, asctime(localtime(&timer)));
   fclose(f);
}



bool_t 
vote_1_svc(char **artist, voteStatus *status, struct svc_req *rqstp)
{
  
  ulong i, num;

 
  if( isVoteOpen == FALSE )
  {
    *status = vsInvalidVoter;
    return TRUE;
  }

  num = list.num;
  for(i=0; i<num; i++)    
  {  
    if( strcmp(list.array[i].name, (*artist) ) == 0 )
    {
      list.array[i].count++;  
      wlog(*artist);
      *status = vsMultipleVotes;
      return TRUE;
    }
  }

  list.array[num].name = (char*)malloc(sizeof(char) * (strlen(*artist)+1));
  if(list.array[num].name == NULL )
    goto errout;

  if ( strcpy(list.array[num].name, (*artist)) == NULL )
    goto errout;

  list.array[num].count = 1;
  list.num++;
  *status = vsVoted; 
  wlog(*artist);
  return TRUE;

errout:
  *status = vsOtherError;
  return FALSE;  
}



bool_t 
results_1_svc(void *x, countList* l, struct svc_req *rqstp)
{
   int i;
   
   FILE *f = fopen("err", "a");
   fprintf(f, "t\n");

   if( list.num == 0 )
   {
      l->num = 0;
      return TRUE;
   }
   
   fprintf(f, "test\n");
   fclose(f);

   for(i=0; i<list.num; i++)
   {
     //(l->array[i]).count = list.array[i].count;

   } 
 
   l->num = list.num;
   return TRUE;
}


int
votesys_1_freeresult(SVCXPRT *transp, xdrproc_t xdr_result,
                     caddr_t result)
{
  xdr_free(xdr_result, result); 
  return 1; 
}
